﻿using System;
using System.Collections.Generic;
using System.IO;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.NamingConventions;

namespace FanMotionWink
{
    public class StorageInstance
    {
        [Serializable]
        public class FanController
        {
            public string CustomName = ""; // 自定义名称
            public string SensorId = "";
            public string TemperaureSrcId = ""; // 温度来源ID
            public bool IsControl = false; // 是否启用控制
            public bool HideInMain = false; // 在main中隐藏
            public string ControlWays = "折线图"; // 控制方式： 常数，折线图
            public List<CurvePoint> curvePoints = new List<CurvePoint>(); // 控制点


            public class FanControllerWeb
            {
                public readonly FanController fc;
                public FanControllerWeb(FanController fc)
                {
                    this.fc = fc;
                }
                public string CustomName => fc.CustomName;
                public string SensorId => fc.SensorId;
                public string TemperaureSrcId => fc.TemperaureSrcId;
                public bool IsControl => fc.IsControl;
                public bool HideInMain => fc.HideInMain;
                public string ControlWays => fc.ControlWays;
                public List<CurvePoint> curvePoints => fc.curvePoints;
            }
        }


        public Dictionary<string, FanController> FanControllerDict = new Dictionary<string, FanController>();
        public bool GlobalEnable = true;
        public bool StartupOnWin = true;

        public List<FanController.FanControllerWeb> FanControllerList
            {
                get
                {
                    var list = new List<FanController.FanControllerWeb>();
                    foreach (var k in FanControllerDict.Keys)
                    {
                        list.Add(new FanController.FanControllerWeb(FindOrCreate(k)));
                    }
                    return list;
                }
            }

        public FanController FindOrCreate(string senId)
        {
            lock (this)
            {
                if (!FanControllerDict.TryGetValue(senId, out var fc))
                {
                    fc = new FanController();
                    fc.SensorId = senId;
                    FanControllerDict.Add(senId, fc);
                }

                return fc;
            }
        }


        public static StorageInstance Instance;
        const string DATA_FOLDER_NAME = "fan-motion-master-win";

        public static string MakesureFolderExists()
        {

            var folderPath = System.Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
            if (folderPath == null)
            {
                throw new Exception("can't read file at document");
            }


            var fp0 = Path.Join(folderPath, DATA_FOLDER_NAME);
            // 检查文件夹是否存在
            if (!Directory.Exists(fp0))
            {
                // 创建文件夹
                Directory.CreateDirectory(fp0);
            }

            var fp = Path.Join(fp0, "config.yaml");
            return fp;
        }

        // 初始化读取
        public static void ReloadFromDiskFile()
        {

            var fp = MakesureFolderExists();
            string nowConfig = "name: unknow";
            try
            {
                nowConfig = File.ReadAllText(fp);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

            var deserializer = new DeserializerBuilder()
                .WithNamingConvention(UnderscoredNamingConvention.Instance)  // see height_in_inches in sample yml 
                .IgnoreUnmatchedProperties()
                .Build();

            Instance = deserializer.Deserialize<StorageInstance>(nowConfig);
            Console.WriteLine(Instance);
        }
        public static void InitLoad()
        {
            // 初始化重复的检查
            if (Instance != null)
            {
                return;
            }
            ReloadFromDiskFile();
        }

        // 现在
        public static void RefreshSave()
        {
            var fp = MakesureFolderExists();
            var deserializer = new YamlDotNet.Serialization.SerializerBuilder()
                .WithNamingConvention(UnderscoredNamingConvention.Instance)  // see height_in_inches in sample yml 
                .Build();
            string nowConfig = deserializer.Serialize(Instance);
            try
            {
                File.WriteAllText(fp, nowConfig);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
    }
}
